package com.xd.pre.modules.tpshop.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xd.pre.common.utils.Result;
import com.xd.pre.modules.tpshop.domain.TpUsers;
import com.xd.pre.modules.tpshop.service.ITpUserLevelService;
import com.xd.pre.modules.tpshop.service.ITpUsersService;
import com.xd.pre.modules.tpshop.service.IViewSpproductattributeBiz;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * //原版（功能正常版） 备份在了GetPrintWriter.java中
 * D:\Program Files\MyEclipse\MyEclipse 10\configuration\org.eclipse.osgi\bundles\99\1\.cp\myeclipse-data\3.3\lib\bytecode\cglib
 *
 * @author lx
 * @since 2020-06-03
 */
@RestController
@RequestMapping("/user")
public class TpUsersController {

    @Autowired
    private ITpUsersService u_biz;
    @Autowired
    private ITpUserLevelService ul_biz;

//    @Autowired
//    private IViewSpproductattributeBiz view_pa_biz;

    //【1】 http://localhost:8080/tpshop_server/user/findAllUser_test_JacksonJsonFilter?userId=1
    @RequestMapping(value = "/findAllUser_test_JacksonJsonFilter", method = RequestMethod.GET)
    public Result findAllUser_test_JacksonJsonFilter(HttpServletRequest request
//				, HttpServletResponse response, PrintWriter out
    ) { //
        String userId = request.getParameter("userId");
        TpUsers user = u_biz.getById(Integer.parseInt(userId));

//        //Spring MVC 更灵活的控制 json 返回（自定义过滤字段）: https://my.oschina.net/diamondfsd/blog/836727	http://www.cnblogs.com/zcw-ios/articles/3343071.html
//        String include= null; String filter = null;
//        ObjectMapper mapper = new ObjectMapper();
//        JacksonJsonFilter jacksonFilter = new JacksonJsonFilter();
//        // 过滤除了 id,title 以外的所有字段，也就是序列化的时候，只包含 id 和 title
//        jacksonFilter.include(TpUsers.class, new String[]{"userId","email"});
//        mapper.setFilterProvider(jacksonFilter);  // 设置过滤器
//        mapper.addMixIn(TpUsers.class, jacksonFilter.getClass()); // 为Article.class类应用过滤器
//        try {
//            include= mapper.writeValueAsString(new TpUsers());
//        } catch (JsonProcessingException e) {
//            System.out.println("findAllUser_test_JacksonJsonFilter方法-1-e.toString(): "+e.toString() );
//        }
//
//        // 序列化所有字段，但是排除 id 和 title，也就是除了 id 和 title之外，其他字段都包含进 json
//        jacksonFilter = new JacksonJsonFilter();
//        jacksonFilter.filter(TpUsers.class, new String[]{"userId","email"} );
//        mapper = new ObjectMapper();
//        mapper.setFilterProvider(jacksonFilter);
//        mapper.addMixIn(TpUsers.class, jacksonFilter.getClass());
//
//        try {
//            filter = mapper.writeValueAsString(new TpUsers());
//        } catch (JsonProcessingException e) {
//            System.out.println("findAllUser_test_JacksonJsonFilter方法-2-e.toString(): "+e.toString() );
//        }

        List<TpUsers> list = u_biz.list();
        Result result = new Result();
        result.setData(list); // user	include		filter

        return result;
    }


    //【4】 http://localhost:8080/tpshop_server/user/View_Sp_product_attribute_list?goodsId=1			// 测试已通过！！
    @RequestMapping(value = "/View_Sp_product_attribute_list", method = RequestMethod.GET)
    public Result View_Sp_product_attribute_list(HttpServletRequest request
//				, HttpServletResponse response, PrintWriter out
    ) { //

        Result result = new Result();

        System.out.println("测试--1-request.getParameter(goodsId)-->: " + request.getParameter("goodsId")); //

        String goodsId = request.getParameter("goodsId"); //

//			List<ViewSpproductattribute> sp_list = null;
//
//			if(null != goodsId && !"".equals(goodsId)) {
//				sp_list = new ArrayList<ViewSpproductattribute>();
//				sp_list = view_pa_biz.find_proAttri_byGoodsId(Integer.parseInt(goodsId));
//				result.setData(sp_list);
//			}else{
////				System.out.println("测试--4-user = null -->: "); //
//				result.setData("goodsId为null");
//			}

        return result;
    }


    // ★★★ 经过自己亲测：这种方式 也可以接收到 安卓传过来的json格式请求  ！！！	这里虽然导入spring-webmvc-3.0.5.RELEASE.jar但是也无法引入produces，暂时先不采取这个方法
//	@RequestMapping(value="/login_json",method=RequestMethod.POST, produces="application/json;charset=UTF-8")
//
//	public Result login_json(@RequestBody String jjj) {
//  	Result result = new Result();
//
//  	System.out.println("测试--1- jjj -->: "+ jjj ); //  	{"jjj":{"username":"11","password":"11"}}
//
//
//  	return result;
//  }


    /*
         * https://zhidao.baidu.com/question/489429323963728332.html:
        String temp="{'data':{'a':[{'b1':'bb1','c1':'cc1'},{'b2':'bb2','c2':'cc2'}]}}";
        JSONObject jodata =JSONObject.fromObject(temp);
        JSONObject joa =JSONObject.fromObject(jodata.get("data").toString());
        JSONArray ja=JSONArray.fromObject(joa.get("a"));
        for(int i=0;i<ja.size();i++){
        JSONObject o=ja.getJSONObject(i);
        if(o.get("b1")!=null){
        System.out.println(o.get("b1"));
        }
    */
    // server端获取 安卓端传来的 json格式请求
//【3】  http://localhost:8080/tpshop_server/user/login_json?{"username":"13052345227","password":"11"}：错误 // ★★★ server端获取 安卓端传来的 json格式请求 就算是用get的提交方式 也不能在浏览器直接 获取结果 ！！！
    @RequestMapping(value = "/login_json", method = RequestMethod.POST)
    public Result login_json(HttpServletRequest request) {
        Result result = new Result();

        StringBuffer sb = null;
        try {

            System.out.println("测试--0.1--->: " + request.getInputStream().toString());

            BufferedInputStream in = new BufferedInputStream(request.getInputStream());

            sb = new StringBuffer(2048);

            int i;
            char c = 0;
            while ((i = in.read()) != -1) {

                sb.append((char) i);    // ★★★ server端 成功获取 安卓端传来的 json格式请求 ★★★
            }
            System.out.println("测试--0.2--->: " + sb);
        } catch (Exception ex) {
            System.out.println("测试--0.3-ex.toString()-->: " + ex.toString());
            ex.printStackTrace();
        }

        String str = sb.toString();

//    	JSONObject  dataJson = (JSONObject) JSONObject.toJSON( sb.toString() ); //  ★★★ fastjson	  不可以 ！
        JSONObject dataJson = JSONObject.fromObject(sb.toString());            //		net.sf.json  也可以 ！
//    	JSONArray ja = JSONArray.fromObject(sb.toString());

        System.out.println("测试--1-dataJson.getString(username)-->: " + dataJson.getString("username")); //
        System.out.println("测试--2-dataJson.get(password).toString()-->: " + dataJson.get("password").toString()); //

        String loginName = dataJson.getString("username");
        String loginPass = dataJson.get("password").toString();

        TpUsers uu = getTpUsersCommon(loginName, loginPass);
//        TpUsers uu = u_biz.login(loginName, loginPass);

        System.out.println("测试--3--->: " + uu.getNickname()); //

        result.setData(uu.getNickname());

        return result;
    }

    private TpUsers getTpUsersCommon(String loginName, String loginPass) {
        LambdaQueryWrapper<TpUsers> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(TpUsers::getNickname, loginName);
        lambdaQuery.eq(TpUsers::getPassword, loginPass);
        return u_biz.getOne(lambdaQuery);
    }


    //问题：如果是json格式的请求怎么破： {"uname":"13052345227","passwd":"11"}
    //目标返回结果格式： http://www.tp-shop.cn/Doc/Index/index/cat_id/74.html
    //【2】 http://localhost:8080/tpshop_server/user/login_string?username=13052345227&password=11			// 测试已通过！！
    @RequestMapping(value = "/login_string", method = RequestMethod.GET)

    public Result login_string(HttpServletRequest request
//			, HttpServletResponse response, PrintWriter out
    ) { //
//		response.setContentType("application/json;charset=UTF-8");
//		response.setContentType("application/xml;charset=UTF-8");
//		response.setContentType("text/json;charset=UTF-8");
//		response.setHeader("pragma", "no-cache");
//		response.setHeader("cache-control", "no-cache");

        Result result = new Result();

        System.out.println("测试--1-request.getParameter(username)-->: " + request.getParameter("username")); //
        System.out.println("测试--2-request.getParameter(password)-->: " + request.getParameter("password")); //


//		PrintWriter out=getConn();
//		JSONObject jo = new JSONObject();

//		String msg ="";
//
//		String userId = "-1";
//

        String loginName = request.getParameter("username"); //
        String loginPass = request.getParameter("password"); //

        TpUsers loginUser = getTpUsersCommon(loginName, loginPass);
//        TpUsers loginUser = u_biz.login(loginName, loginPass);
        //  0 保密 1 男(true) 2 女'

        if (null != loginUser && !"".equals(loginUser)) {
//			jo.put("result", loginUser.getNickname());
            System.out.println("测试--3-loginUser.getNickname()-->: " + loginUser.getNickname()); //
            result.setData(loginUser);
        } else {
//			jo.put("result", "此次查询失败，数据库没有此用户！！");
            System.out.println("测试--4-user = null -->: "); //
            result.setData("user为null");
        }

//		out.print(jo);
//		out.flush();
//		out.close();

        return result;
    }


    //【1】 http://localhost:8080/tpshop_server/user/update_user_info?login_uId=1&loginPass=11			// 测试已通过！！
    @RequestMapping(value = "/update_user_info", method = RequestMethod.GET)

    public Result update_user_info(HttpServletRequest request) {

        System.out.println("测试--1-request.getParameter(login_uId)-->: " + request.getParameter("login_uId")); //
        System.out.println("测试--2-request.getParameter(head_pic)-->: " + request.getParameter("head_pic")); //
        System.out.println("测试--3-9-request.getParameter(nickNameStr)-->: " + request.getParameter("nickNameStr"));  // 3-9乱码
        System.out.println("测试--4-request.getParameter(sex)-->: " + request.getParameter("sex")); //
        System.out.println("测试--5-request.getParameter(birthday)-->: " + request.getParameter("birthday")); //

//    	String order =new String(request.getParameter("order").getBytes("iso-8859-1"),"utf-8") ;// 接收订单信息
        try {
            System.out.println("测试--9-3-request.getParameter(nickNameStr)-->: " +
                    new String(request.getParameter("nickNameStr").getBytes("iso-8859-1"), "utf-8")                    // 9-3乱码 解决办法
            );
        } catch (UnsupportedEncodingException e) {
            System.out.println("e.toString(): " + e.toString());
            e.printStackTrace();
        } //

        String userId = request.getParameter("login_uId"); //
        String headPic = request.getParameter("head_pic"); //
        String nickname = null;  // 3-9乱码
        try {
            nickname = new String(request.getParameter("nickNameStr").getBytes("iso-8859-1"), "utf-8");                    // 9-3乱码 解决办法

        } catch (UnsupportedEncodingException e) {
            System.out.println("e.toString(): " + e.toString());
            e.printStackTrace();
        } //
        String sex = request.getParameter("sex"); //
        String birthday = request.getParameter("birthday"); //

        Result result = new Result();

        if (null != nickname && !"".equals(nickname) && null != sex && !"".equals(sex) &&
                null != birthday && !"".equals(birthday) && null != userId && !"".equals(userId)) {

            TpUsers uu = new TpUsers();
            uu.setHeadPic(headPic);
            uu.setNickname(nickname);
            uu.setSex(Integer.parseInt(sex));
            uu.setBirthday(Integer.parseInt(birthday));
            uu.setUserId(Integer.parseInt(userId));
            boolean b = u_biz.updateById(uu);
            int res = b ? 1 : -1;
//            int res = u_biz.update_user_info(headPic, nickname, Integer.parseInt(sex), Integer.parseInt(birthday), Integer.parseInt(userId));
            System.out.println("修改更新loginuser的结果res：" + res);

            result.setData(String.valueOf(res)); // string 比较好处理一点 ！！
        }

        return result;
    }

    //【5】 http://localhost:8080/tpshop_server/user/inset_user_info_1?mobile=13052345228&level_id=1			//验证已通过
    @RequestMapping(value = "/inset_user_info_1", method = RequestMethod.GET)

    public Result inset_user_info_1(HttpServletRequest request) {
        Result result = new Result();

        String mobile = request.getParameter("mobile"); //
        String level_id = request.getParameter("level_id"); //
        if (null != mobile && !"".equals(mobile) && null != level_id && !"".equals(level_id)) {
            TpUsers uu = new TpUsers();
            uu.setMobile(mobile);
            uu.setLevelId(Integer.parseInt(level_id));
            boolean save = u_biz.save(uu);
            int res = save ? 1 : -1;
//            int res = u_biz.inset_user_info_1(mobile, Integer.parseInt(level_id));
            System.out.println("修改更新loginuser的结果res：" + res);

            result.setData(String.valueOf(res)); // string 比较好处理一点 ！！
        }
        return result;
    }




































































	/*
		//问题：如果是json格式的请求怎么破： {"uname":"13052345227","passwd":"11"}
		//目标返回结果格式： http://www.tp-shop.cn/Doc/Index/index/cat_id/74.html
		// http://localhost:8080/tpshop_server/login_String1?loginName=13052345227&loginPass=11			// 测试已通过！！
		@Action(value="login_String1")
		public String login_String1(){
			PrintWriter out=getConn();
			JSONObject jo = new JSONObject();

			String msg ="";

			String userId = "-1";

			System.out.println("打印的请求参数--loginName: "+loginName);// 如果是json格式的请求，则这里接收到的为null !!!
			System.out.println("打印的请求参数--loginPass: "+loginPass);// 如果是json格式的请求，则这里接收到的为null !!!

			TpUsers loginUser = u_biz.login(loginName, loginPass);

			if(null != loginUser && !"".equals(loginUser)) {
				jo.put("result", loginUser);
			}else{
				jo.put("result", "此次查询失败，数据库没有此用户！！");
			}

//			if(u == null || u.equals("")) {
//				msg = "请填写账号或密码";
//			}else{
//				msg = "登陆成功";
//				userId = u.getUserId()+"";
//			}


			out.print(jo);
			out.flush();
			out.close();

			return null;
		}

	*/


//	@Resource(name="TpUsersBiz")
//	private ITpUsersBiz u_biz;
//
//	@Resource(name="TpUserLevelBiz")
//	private ITpUserLevelBiz ul_biz;
//
//	public ITpUserLevelBiz getUl_biz() {
//		return ul_biz;
//	}
//	public void setUl_biz(ITpUserLevelBiz ul_biz) {
//		this.ul_biz = ul_biz;
//	}
//
//	private String loginName;	// app端需用 RequestParams类 的参数 请求
//	private String loginPass;	// app端需用 RequestParams类 的参数 请求
//
//	public ITpUsersBiz getU_biz() {
//		return u_biz;
//	}
//	public void setU_biz(ITpUsersBiz u_biz) {
//		this.u_biz = u_biz;
//	}
//	public String getLoginName() {
//		return loginName;
//	}
//	public void setLoginName(String loginName) {
//		this.loginName = loginName;
//	}
//	public String getLoginPass() {
//		return loginPass;
//	}
//	public void setLoginPass(String loginPass) {
//		this.loginPass = loginPass;
//	}


    // http://localhost:8080/tpshop_server/login_json?loginName2=13052345227&loginPass2=11
//	@Action(value="login_json")	// 改动处2：@RequestMapping(value="/login_json",method=RequestMethod.POST)
//
//	public String login_json(HttpServletRequest request){	//
////			@RequestParam("loginName2") String loginName2,
////			@RequestParam("loginPass2") String loginPass2
//			String loginName2 = request.getParameter("loginName2");
//			String loginPass2 = request.getParameter("loginPass2");
//
//
//
//			System.out.println("打印的请求参数--loginName: "+loginName2);// 如果是json格式的请求，则这里接收到的为null !!!
//			System.out.println("打印的请求参数--loginPass: "+loginPass2);// 如果是json格式的请求，则这里接收到的为null !!!
//
//
////		if (loginName2==null||loginPass2 == null ) {
////
////		}
////		TpUsers loginUser = u_biz.login(loginName2, loginPass2);
//
//
//		return null;
//	}


//    public PrintWriter getConn() {
//        HttpServletResponse response = ServletActionContext.getResponse();
//        response.setContentType("text/html; charset=utf-8");
//        try {
//            PrintWriter out = response.getWriter();
//            return out;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }


}
